﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    /// <summary>
    /// 日常开支
    /// </summary>
    public class UsualFinanceController : Controller
    {
        RefeModel model = new RefeModel(); 
        //
        // GET: /UsualFinanceC/
        private readonly IUsualFinanceService workGroupServiceImpl = ServiceLocator.Instance.GetService<IUsualFinanceService>();
        public ActionResult Index()
        {
            return View();
        }
        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public JsonResult AddAndConfirm(UsualFinanceDto roductInBillDto)
        {
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return Json("0", JsonRequestBehavior.AllowGet);
            }
            //保存(或更新)
            string actionResult = AddPrivate(roductInBillDto, isConfirm);
            ViewBag.PostState = actionResult;
            return Json(actionResult, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = workGroupServiceImpl.GetUsualFinance(id);
         //   BindProjectType(billModel.ProjectType.ToString());
            return View(billModel);
        }
        #endregion
        #region 日常财务
        private string AddPrivate(UsualFinanceDto roductInBillDto,bool isConfirm)
        {

            
            #region 主数据行处理
            roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
            #endregion
            #region 明细行数据处理
            var model = new ProductCheckBillModel();

            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<UsualFinanceDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return ("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
            detailItems.Each(item =>
            {
                item.UsualFinanceID = checkId;
                if (IsGuid(item.OperatorName))
                {
                    item.OperatorID = Guid.Parse(item.OperatorName);
                }
                if (item.Id == null || item.Id.Equals(Guid.Empty))
                {
                    item.Id = Guid.Empty;
                }
                if (item.HandlingTime <= DateTime.Parse("1900-01-01"))
                {
                    item.HandlingTime = DateTime.Now;
                }
                else {
                    if (item.HandlingTime.Hour > 0)
                    {
                        item.HandlingTime = item.HandlingTime.AddHours(8);
                    }
                }
            });

            #endregion

            
            if (ModelState.IsValid)
            {
                try
                {
                    #region 操作正常发货数据
                    if (isConfirm)
                    {
                        roductInBillDto.BillState = 1;
                    }
                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        roductInBillDto.UpdateDate = DateTime.Now;
                        roductInBillDto.UpdateID = roductInBillDto.CreateID;
                        var id = this.workGroupServiceImpl.UpdateUsualFinanceDetail(roductInBillDto,detailItems);
                    }
                    else
                    {
                        var id = workGroupServiceImpl.AddUsualFinanceDetail(roductInBillDto,detailItems);
                    }
                    return "9";
                    #endregion
                }
                catch (Exception ex)
                {
                    return "-1";
                }
                
            }

            return "0";
        }
        [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode,Guid? billId)
        {
            var wg = new UsualFinanceDto();
            //wg.HandlingTime = DateTime.Today;
            if (billId.HasValue && !billId.Value.Equals(Guid.Empty))
            {
                Guid wid = Guid.Empty;
                Guid.TryParse(billId.Value.ToString(), out wid);
                wg = workGroupServiceImpl.GetUsualFinance(wid);
            }
            else
            {
                IOrgService orgServiceImpl = ServiceLocator.Instance.GetService<IOrgService>();
               var org= orgServiceImpl.GetOrg(orgCode.Trim());
               wg.OrgId = org.Id;
               wg.OrgName = org.Name;
            }
            //BindProjectType(wg.ProjectType.ToString());
            ViewBag.OrgCode = orgCode;
            return View(wg);
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(UsualFinanceDto workGroup)
        {

            #region 明细行数据处理


            //var result = Request.Form["hidProductBillItems"];
            //var detailItems = model.ConvertJosnToClass<ProductDeliveryBillDetailDto>(result);
            //if (!string.IsNullOrEmpty(result) && detailItems == null)
            //{
            //    return Content("-1");//明细行异常
            //}
            //var checkId = Guid.Empty;
            //if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            //{
            //    checkId = roductInBillDto.Id;
            //}
            //detailItems.Each(item =>
            //{
            //    item.ProductDeliveryBillID = checkId;
            //    if (item.ID == null || item.ID.Equals(Guid.Empty))
            //    {
            //        item.ID = Guid.Empty;
            //    }
            //});

            #endregion

            //var type = this.HttpContext.Request.Form["ProjectType"];
            //workGroup.ProjectType = type == "0" ? 0 : 1;

            //#region 组织机构
            //var orgCode = this.HttpContext.Request.Form["HidOrgCode"];
            //IOrgService orgServiceImpl = ServiceLocator.Instance.GetService<IOrgService>();
            //workGroup.OrgId = orgServiceImpl.GetOrg(orgCode).Id;

            //ViewBag.OrgCode = orgCode;

            //var csID = Request.Form["OperatorName_val"];
            //if (!string.IsNullOrEmpty(csID))
            //{
                
            //    workGroup.OperatorId = Guid.Parse(csID);
            //}
            //if (workGroup.OperatorId == null || workGroup.OperatorId.Equals(Guid.Empty))
            //{
            //    BindProjectType(workGroup.ProjectType.ToString());
            //    ModelState.AddModelError("OperatorId", "经办人不能为空！");
            //    return View(workGroup);
            //}
            //#endregion

            //if (ModelState.IsValid)
            //{
            //    if (!workGroup.Id.Equals(Guid.Empty))
            //    {
            //        this.workGroupServiceImpl.Update(workGroup);
            //    }
            //    else
            //    {
            //        workGroup.Operation_ID = UserModel.GetLoginUserId(this.HttpContext);
            //        workGroup.Operation_Time = DateTime.Now;
            //        this.workGroupServiceImpl.Add(workGroup);
            //    }
            //    ViewBag.PostState = 9;
            //}
            //BindProjectType(workGroup.ProjectType.ToString());
            return View(workGroup);
        }

        public ActionResult Delete(Guid billId,Guid detailId)
        {
            workGroupServiceImpl.Delete(billId, detailId);
            return Content("9");
        }
        #endregion
        #region 获得日常财务列表
        [NoAuthorizated("GetJsonOfBills")]
        public ActionResult GetJsonOfBills()
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            var workGroupService = workGroupServiceImpl.GetUsualFinances();
            if (workGroupService != null && workGroupService.Count() != 0)
            {
                workGroupService.Select(t => { t.ProjectTypeName = t.ProjectType == 0 ? "收入" : "支出"; return t; });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(workGroupService);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + workGroupService.Count() + "\"}";
                return Content(target);
            }
            return View();
            */
            #endregion
            return Content(new BLLQuery().GetUsualFinances(this.HttpContext));
        }
        /// <summary>
        /// 根据发货ID，获得发货所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
        [NoAuthorizated("GetJsonOfBillDetails")]
        public ActionResult GetJsonOfBillDetails(Guid billId)
        {
            
            var billDetails = workGroupServiceImpl.GetUsualFinanceDetails(billId).ToList();
            if (billDetails != null && billDetails.Count() != 0)
            {
                var jsonResult = billDetails;//.Select(b => { b.DeleteState = b.Deleted == 0 ? "正常" : "已删除"; return b; });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + billDetails.Count() + "\"}";
                return Content(target);
            }
            return Content("");
        }
        #endregion
        #region 深圳业务
         public ActionResult SZIndex()
        {
            return View();
        }
        #endregion
        #region 收入支出
         private void BindProjectType(string type)
         {
             var list = new List<SelectListItem> { 
                 new SelectListItem{ Text="收入", Value="0"},
                 new SelectListItem{ Text="支出", Value="1"}
            };
             if (!string.IsNullOrEmpty(type))
             {
                 list.ForEach(t => { if (t.Value.ToString() == type) { t.Selected = true; } });
             }
             ViewBag.ProjectType = list;
         }
         [NoAuthorizated("SelectProductTypeItems")]
         public ActionResult SelectProductTypeItems()
         {
             var refeList = model.GetRefeByModuleName(RefeTypeOption.项目名称);
             return View();
         }
        [NoAuthorizated("GetProjectTypeJsons")]
         public ActionResult GetProjectTypeJsons()
         {

             var refeList = model.GetRefeByModuleName(RefeTypeOption.项目名称);
             if (refeList != null && refeList.Count() != 0)
             {
                 var jsonResult = refeList;
                 var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                 target = "{\"Rows\":" + target + ",\"Total\":\"" + refeList.Count() + "\"}";
                 return Content(target);
             }
             return Content("");
         }
         #endregion
        #region 删除订单明细（假删除）
        [NoAuthorizated("DeleteItem")]
        public ActionResult DeleteItem(Guid billId, string ids)
        {
            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                workGroupServiceImpl.ConvertUsualFinanceDeleteState(billId, guidIds);
                return Content("9");
            }
          
            return Content("0");
        }
        #endregion
        private bool IsGuid(string str)
        {
            if (str.IsNullOrEmpty())
            {
                return false;
            }
            Guid guid;
            return Guid.TryParse(str, out guid);
        }
    }
}
